<?php
/*
 * Copyright (c) 2022.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace app\listener;

use Swoole\Timer;
use think\App;
use think\facade\Log;
use think\swoole\Manager;

class SwooleTimer
{

    protected $manager;

    public function __construct(App $app)
    {
        $this->manager = $app->make(Manager::class);
    }

    public function handle()
    {
        $this->manager->addWorker(function () {
            $this->manager->runWithBarrier(function () {
                $this->process();
            });
        }, 'dk-timer');
    }

    public function process(): void
    {
        Timer::tick(5000, function () {
            try {
                event('onTimer_5');
            } catch (\Throwable $th) {
                Log::channel('swoole')->write('报错了' . $th->getMessage());
            }
        });
        $tasks = event('tasks');
        foreach ($tasks as $key => $task) {
            if (is_array($task)) {
                foreach ($task as $k => $val) {
                    $this->tick($val);
                }
            } else {
                $this->tick($task);
            }
        }
    }


    public function tick($task)
    {
        if ($task['time'] && $task['handler'] && $task['class']) {
            $time = abs(intval($task['time'])) * 1000;
            Timer::tick($time, function () use ($task) {
                try {
                    $class = new $task['class'];
                    $class->{$task['handler']}();
                } catch (\Throwable $th) {
                    Log::channel('swoole')->write('报错了' . $th->getMessage());
                }
            });
        }
    }
}
